
// 模拟食谱数据
const mockRecipes = [
    {
        id: 1,
        title: "Beef stew with potatoes and carrots",
        image:"./images/Beef stew with potatoes and carrots.jpg",
        ingredients: ["beef", "potatoes", "carrots","cooking wine","octagon","sugar","Light soy sauce","Fuel consumption","dark soy sauce","tomato"],
        steps: [
            "First, simmer the beef over low heat until it is 70% cooked. Then, separate the meat from the soup and serve it.",
            "Stir-fry scallions, ginger, Sichuan pepper, star anise, bay leaves, cinnamon and other seasonings in the pot until fragrant",
            "Add Onions and stir-fry the beef until fragrant.",
            "Stir-fry evenly with dark soy sauce, light soy sauce, oyster sauce and cooking wine.",
            "In another pan, stir-fry the potatoes and carrots",
            "Remove the stir-fried potatoes and carrots.",
            "Stir-fry the tomatoes until they release juice.",
            "Pour the stir-fried beef into the tomato juice while it's still hot.",
            "Heat the beef soup over medium heat and simmer it slowly. When they are 90% cooked, add the potatoes and carrots from step 6 and season with salt",
            "Medium to high fire. When cooked, you can add a little chicken essence before taking it off the heat",
            "complete!!"
        ],
        time: "15Minutes",
        difficulty: "easzy",
        servings: "For two people "
    },
    {
        id: 2,
        title: "shredded pork with green pepper",
        image: "./images/shredded pork with green pepper.jpg",
        ingredients: ["pork", "Green pepper", "garlic", "Broad bean paste","Light soy sauce","Fuel consumption","dark soy sauce","cornstarch"],
        steps: [
            "Wash the green peppers thoroughly and soak them in salt water to remove any residual pesticides",
            "Cut the meat into thin shreds and mix well with soy sauce, light soy sauce, oyster sauce and cornstarch",
            "Heat the pan with cold oil and stir-fry the shredded meat",
            "When the oil is hot, stir-fry the scallions, ginger and garlic until fragrant. Add half a spoonful of broad bean paste and stir-fry until it turns red. Then add the green peppers and stir-fry for a moment. Add the shredded meat. Stir-fry for a while, then add water and stir-fry for a few minutes. Add a little salt. Since the broad bean paste is salty, a little salt is enough. Remove from the heat.",
            "complete!!"
        ],
        time: "10Minutes",
        difficulty: "easzy",
        servings: "For three people"
    },
    {
        id: 3,
        title: "Mapo Tofu",
        image: "./images/Mapo Tofu.jpg",
        ingredients: ["tofu", "Minced meat", "Broad bean paste", "Ground Sichuan pepper", "Chili powder", "Pepper powder", "Water starch", "Scallion"],
        steps: [
            "Prepare the materials. Cut the scallions into small sections",
            "Heat oil in a wok, stir-fry the minced meat until cooked, then set it aside",
            "Add more oil to the pan and stir-fry the broad bean paste until fragrant",
            "Add water, then put in the Sichuan pepper grains, chili powder and ground pepper. Simmer over low heat for 7 minutes, and then add the stir-fried minced meat",
            "Cut the tofu into small pieces and put them in",
            "After boiling for a few minutes, add the water starch and bring the soup to a boil again",
            "Serve it, sprinkle with chopped Sichuan pepper, and then sprinkle with chopped scallions",
            "complete!!"
        ],
        time: "15Minutes",
        difficulty: "simple",
        servings: "For three people"
    },
];

// 主页功能
if (document.getElementById('ingredient-input')) {
    // 已选食材数组
    const selectedIngredients = [];
    const ingredientInput = document.getElementById('ingredient-input');
    const addButton = document.getElementById('add-ingredient');
    const selectedIngredientsContainer = document.getElementById('selected-ingredients');
    const generateButton = document.getElementById('generate-recipe');
    const recipeGrid = document.getElementById('recipe-grid');

    // 添加食材
    addButton.addEventListener('click', () => {
        const ingredient = ingredientInput.value.trim();
        if (ingredient && !selectedIngredients.includes(ingredient)) {
            selectedIngredients.push(ingredient);
            renderSelectedIngredients();
            ingredientInput.value = '';
        }
    });

    // 回车键添加食材
    ingredientInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            addButton.click();
        }
    });

    // 渲染已选食材
    function renderSelectedIngredients() {
        if (selectedIngredients.length === 0) {
            selectedIngredientsContainer.innerHTML = '<p class="empty-state">Start adding the ingredients...</p>';
            return;
        }

        selectedIngredientsContainer.innerHTML = '';
        selectedIngredients.forEach((ingredient, index) => {
            const tag = document.createElement('div');
            tag.className = 'ingredient-tag';
            tag.innerHTML = `
                ${ingredient}
                <button class="remove-tag " data-index="${index}">
                    <i class="fa fa-times-circle"></i>
                </button>
            `;
            selectedIngredientsContainer.appendChild(tag);
        });

        // 添加删除事件
        document.querySelectorAll('.remove-tag').forEach(button => {
            button.addEventListener('click', (e) => {
                const index = parseInt(e.currentTarget.dataset.index);
                selectedIngredients.splice(index, 1);
                renderSelectedIngredients();
            });
        });
    }

    // 生成食谱
    generateButton.addEventListener('click', () => {
        if (selectedIngredients.length === 0) {
            alert('Please add the ingredients first');
            return;
        }

        // 筛选包含至少一个所选食材的食谱
        const matchedRecipes = mockRecipes.filter(recipe => {
            return selectedIngredients.some(ingredient => 
                recipe.ingredients.includes(ingredient)
            );
        });

        renderRecipes(matchedRecipes);
    });

    // 渲染食谱列表
    function renderRecipes(recipes) {
        if (recipes.length === 0) {
            recipeGrid.innerHTML = '<p class="empty-state">No matching recipe was found. Please try adding other ingredients</p>';
            return;
        }

        recipeGrid.innerHTML = '';
        recipes.forEach(recipe => {
            const card = document.createElement('div');
            card.className = 'recipe-card';
            card.innerHTML = `
                <img src="${recipe.image}" alt="${recipe.title}" class="recipe-image">
                <div class="recipe-content">
                    <h3 class="recipe-title">${recipe.title}</h3>
                    <div class="recipe-meta">
                        <span class="cook-time">
                            <i class="fa fa-clock-o"></i> ${recipe.time}
                        </span>
                        <span class="difficulty">
                            <i class="fa fa-signal"></i> ${recipe.difficulty}
                        </span>
                    </div>
                    <a href="recipe-detail.html?id=${recipe.id}" class="view-recipe">
                        View details
                    </a>
                </div>
            `;
            recipeGrid.appendChild(card);
        });
    }
}

// 详情页功能
if (document.getElementById('recipe-detail')) {
    const recipeId = new URLSearchParams(window.location.search).get('id');
    const recipeLoading = document.getElementById('recipe-loading');
    const recipeContent = document.getElementById('recipe-content');
    const recipeError = document.getElementById('recipe-error');
    const detailImage = document.getElementById('detail-image');
    const detailTitle = document.getElementById('detail-title');
    const detailTime = document.getElementById('detail-time');
    const detailDifficulty = document.getElementById('detail-difficulty');
    const detailServings = document.getElementById('detail-servings');
    const detailIngredients = document.getElementById('detail-ingredients');
    const detailSteps = document.getElementById('detail-steps');

    // 模拟加载延迟
    setTimeout(() => {
        const recipe = mockRecipes.find(r => r.id === parseInt(recipeId));
        if (!recipe) {
            recipeLoading.classList.add('hidden');
            recipeError.classList.remove('hidden');
            return;
        }

        // 填充食谱详情
        detailImage.src = recipe.image;
        detailImage.alt = recipe.title;
        detailTitle.textContent = recipe.title;
        detailTime.textContent = recipe.time;
        detailDifficulty.textContent = recipe.difficulty;
        detailServings.textContent = recipe.servings;

        // 渲染食材列表
        detailIngredients.innerHTML = '';
        recipe.ingredients.forEach(ingredient => {
            const li = document.createElement('li');
            li.textContent = ingredient;
            detailIngredients.appendChild(li);
        });

        // 渲染步骤列表
        detailSteps.innerHTML = '';
        recipe.steps.forEach((step, index) => {
            const li = document.createElement('li');
            li.className = 'step-item';
            li.innerHTML = `
                <span class="step-number">${index + 1}</span>
                ${step}
            `;
            detailSteps.appendChild(li);
        });

        // 显示内容
        recipeLoading.classList.add('hidden');
        recipeContent.classList.remove('hidden');
    }, 800);
}